package com.magicalcoder.pigeon.client;


import com.magicalcoder.pigeon.common.constant.Status;
import com.magicalcoder.pigeon.common.message.PigeonRequest;
import com.magicalcoder.pigeon.common.message.PigeonResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by hzhedongyu on 2017/5/26.
 */
public class ClientProxy implements InvocationHandler {

    private String serviceName;//具体对应服务端哪个服务名称便于查找

    public ClientProxy(String serviceName) {
        this.serviceName = serviceName;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        PigeonRequest request = new PigeonRequest();
        request.setRequestId(UUID.randomUUID().toString());
        request.setInterfaceName(method.getDeclaringClass().getName());
        request.setMethodName(method.getName());
        request.setParams(args);
        request.setParamTypes(method.getParameterTypes());
        //开始连接服务端并且调用
//        System.out.println("请求"+request.getRequestId());
        NettyClientHandler handler = ClientHandlerManager.get().chooseOneHandler(serviceName);
        ClientFuture future = handler.requestServer(request);
        PigeonResponse response = future.get(30, TimeUnit.SECONDS);
//        System.out.println("返回"+request.getRequestId());

        if(response==null){
            handler.removeRequestFromHoldMap(request.getRequestId());
            throw new NullPointerException("通信异常：超时,无法获取服务端返回");
        }
        if(response.getCode()== Status.OK){
            return response.getInfo();
        }else if(response.getCode() == Status.EXCEPTION){
            Exception e = (Exception)response.getInfo();
//            e.printStackTrace();
            throw e.getCause();
        }else {
            throw new RuntimeException("通信失败：未捕获异常");
        }
    }


}
